import * as Constants from './Constants'
import * as utils from './utils'
import * as echarts from 'echarts'
let profile = {
  arrPoint: [], // 经纬度点 转换坐标 集合
  arrLX: [], //距离集合 加上间隔点的
  ponits: [], // xyz 集合
  // distance: 0, //总距离
  heightArr: []
}
let cartesian = null
let distance = 0 // 总距离
// 划线
var PolyLinePrimitive = (function () {
  var that = this
  function _(positions) {
    console.log(positions);
    this.options = {
      name: '直线',
      polyline: {
        show: true,
        positions: [],
        material: new Cesium.Color(0, 124 / 255, 247 / 255, 1),
        // material: Cesium.Color.CHARTREUSE,
        width: 3,
        clampToGround: true,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    }
    this.positions = positions
    this._init()
  }

  _.prototype._init = function () {
    var _self = this
    var _update = function () {
      return _self.positions
    }
    // 实时更新polyline.positions
    this.options.polyline.positions = new Cesium.CallbackProperty(_update, false)
    const line = viewers.entities.add(this.options)
    // measureFeature_line.push(line)
  }

  return _
})()

// 创建面
var PolygonPrimitive = (function () {
  function _(positions) {
    this.options = {
      name: '多边形',
      polygon: {
        hierarchy: [],
        material: new Cesium.Color(0, 124 / 255, 247 / 255, 0.5),
        // material: Cesium.Color.GREEN.withAlpha(0.5)
        // heightReference:20000
        clampToGround: true,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    }

    this.hierarchy = { positions }
    this._init()
  }

  _.prototype._init = function () {
    var _self = this
    var _update = function () {
      return _self.hierarchy
    }
    // 实时更新polygon.hierarchy
    this.options.polygon.hierarchy = new Cesium.CallbackProperty(_update, false)
    const _polygon = viewers.entities.add(this.options)
  }

  return _
})()
// 空间两点距离计算函数
function getSpaceDistance(positions) {
  var distance = 0
  for (var i = 0; i < positions.length - 1; i++) {
    var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i])
    var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1])
    /** 根据经纬度计算出距离**/
    var geodesic = new Cesium.EllipsoidGeodesic()
    geodesic.setEndPoints(point1cartographic, point2cartographic)
    var s = geodesic.surfaceDistance
    // 返回两点之间的距离
    s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2))
    distance = distance + s
  }
  return Number(distance.toFixed(2))
}
var viewers

export default class Draw {
  constructor(viewer, config, label) {
    /**cesium实例对象 */
    this.viewer = viewer
    viewers = viewer
    // this.callback = callback
    /**绘制要素的相关配置
       * 默认配置
       * {
          borderColor: Cesium.Color.BLUE,  边框颜色
          borderWidth: 2, 边框宽度
          material: Cesium.Color.GREEN.withAlpha(0.5),填充材质
      }
      */
    this.config = config || {
      borderColor: Cesium.Color.BLUE,
      borderWidth: 2,
      material: Cesium.Color.GREEN.withAlpha(0.5)
    }
    /**存贮绘制的数据 坐标 */
    this.infoDetail = { point: [], line: [], rectangle: [], circle: [], planeSelf: [] }
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)

    this._polygon = null //活动面
    this._polygonLast = null //最后一个面
    this._positions = [] //活动点
    this._entities_point = [] //脏数据
    this._entities_polygon = [] //脏数据
    this._polygonData = null //用户构造面
    this.p = []
    this.label = label

    this.t = 0.4
    this.floatingPoint = null //标识点
    this._gatheringPlace = null //活动集结地
    this._gatheringPlaceLast = null //最后一个集结地
    this._entities_gatheringPlace = [] //脏数据
    this._gatheringPlaceData = null //用于构造集结地数据
    this.lonLatArr = []

    // 直线监听
    this._straightArrow = null //活动箭头
    this._straightArrowLast = null //最后一个箭头

    this._entities_point = [] //脏数据
    this._entities_straightArrow = [] //脏数据
    this._straightArrowData = null //用于构造箭头数据

    // 攻击箭头

    this.objId = Number(new Date().getTime() + '' + Number(Math.random() * 1000).toFixed(0))
    this.pointImageUrl = 'img/point.png'
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.fillMaterial = Cesium.Color.RED.withAlpha(0.8)
    this.outlineMaterial = new Cesium.PolylineDashMaterialProperty({
      dashLength: 16,
      color: Cesium.Color.fromCssColorString('#f00').withAlpha(0.7)
    })
    this.positions = [] //控制点
    this.state = -1 //state用于区分当前的状态 0 为删除 1为添加 2为编辑

    this.arrowEntity = null
    this.pointArr = [] //中间各点
    this.selectPoint = null
    this.clickStep = 0 //用于控制点的移动结束
    this.modifyHandler = null

    // 钳击箭头

    this.pointImageUrl = 'img/point.png'
    this.fillMaterial = Cesium.Color.YELLOW.withAlpha(0.8)
    this.outlineMaterial = new Cesium.PolylineDashMaterialProperty({
      dashLength: 16,
      color: Cesium.Color.fromCssColorString('#f00').withAlpha(0.7)
    })
    // $this.floatPoint  arrowEntity
    this.state = -1 //state用于区分当前的状态 0 为删除 1为添加 2为编辑
    this.floatPoint = null
    this.pointArr = []
    this.selectPoint = null
    this.clickStep = 0 //用于控制点的移动结束
    this.modifyHandler = null

    // 自由线

    this._entities_line = []
    this.entityCollection = []

    // 曲线旗标
    this.identificationPoint = null //标识点位
    this.CurveFlag = null
    this.CurveFlagLast = null // 曲线旗标数据
    this.positions = [] // 经纬度
    this.entitiesPoint = [] // 实体点位
    this.entitiesCurveFlag = []
    this.CurveFlagData = null
    this.DrawStartEvent = new Cesium.Event() //开始绘制事件
    this.DrawEndEvent = new Cesium.Event() //结束绘制事件

    // 剖面分析
    this.interData = []
    this._entities_billboard = []


  }
  // 测量距离
  darwdistance() {
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)

    // 取消双击事件-追踪该位置
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    var positions = []
    var poly = null
    var distance = 0
    let that = this

    this.handler.setInputAction(function (movement) {
      var cartesian = that.getCatesian3FromPX(movement.endPosition)
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
        if (positions.length >= 1) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
          distance = getSpaceDistance(positions)
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    that.handler.setInputAction(movement => {
      var cartesian = that.getCatesian3FromPX(movement.position)
      if (Cesium.defined(cartesian)) {
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        positions.push(cartesian)
        var textDisance
        if (distance > 1000) {
          textDisance = (distance / 1000).toFixed(2) + 'km'
        } else {
          textDisance = distance + 'm'
        }
        that.viewer.entities.add({
          name: '空间直线距离',
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.DEEPSKYBLUE,
            outlineWidth: 3,
            // clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
          label: {
            text: textDisance,
            font: '18px sans-serif',
            fillColor: Cesium.Color.DARKORANGE,
            fillColor: Cesium.Color.RED,
            // pixelOffset: new Cesium.Cartesian2(20, -20),
            clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          }
        })
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(function (movement) {
      // that.handler.destroy() // 关闭事件句柄
      that.destroy()
      positions.pop() // 最后一个点无效
      that.label.style.display = 'none'

    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  // 测量面积
  clickCemj() {
    // this.handler.destroy()
    this.destroy()
    var viewer  = this.viewer
    var $this = this
    var that = this
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    console.log(this.handler);
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    // 鼠标事件
    var positions = []
    var tempPoints = []
    var polygon = null
    this.handler.setInputAction(function (movement) {
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'
      var cartesian = that.getCatesian3FromPX(movement.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(function (movement) {
      var cartesian = that.getCatesian3FromPX(movement.position)
      if (Cesium.defined(cartesian)) {
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        positions.push(cartesian)
        that.createPoint(cartesian)
        // 在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1])
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
        var heightString = cartographic.height
        tempPoints.push({
          lon: longitudeString,
          lat: latitudeString,
          hei: heightString
        })
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(movement => {
      // this.handler.destroy()
      this.destroy()
      positions.pop()
      var polyCenter = Cesium.BoundingSphere.fromPoints(positions).center
      var textArea = getArea(tempPoints) + 'km²'
      const _label = $this.viewer.entities.add({
        name: '多边形面积',
        position: polyCenter,
        label: {
          text: textArea,
          font: '16px sans-serif',
          fillColor: Cesium.Color.DARKORANGE,

          clampToGround: true,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
      })
      that.label.style.display = 'none'
    
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

    var radiansPerDegree = Math.PI / 180.0 // 角度转化为弧度(rad)
    var degreesPerRadian = 180.0 / Math.PI // 弧度转化为角度

    // 计算多边形面积
    function getArea(points) {
      var res = 0
      // 拆分三角曲面
      for (var i = 0; i < points.length - 2; i++) {
        var j = (i + 1) % points.length
        var k = (i + 2) % points.length
        var totalAngle = Angle(points[i], points[j], points[k])

        // var dis_temp1 = distance(positions[i], positions[j])
        // var dis_temp2 = distance(positions[j], positions[k])
        var dis_temp1 = getSpaceDistance([positions[i], positions[j]])
        var dis_temp2 = getSpaceDistance([positions[j], positions[k]])
        res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle))
      }

      return (res / 1000000.0).toFixed(4)
    }

    /* 角度 */
    function Angle(p1, p2, p3) {
      var bearing21 = Bearing(p2, p1)
      var bearing23 = Bearing(p2, p3)
      var angle = bearing21 - bearing23
      if (angle < 0) {
        angle += 360
      }
      return angle
    }
    /* 方向 */
    function Bearing(from, to) {
      var lat1 = from.lat * radiansPerDegree
      var lon1 = from.lon * radiansPerDegree
      var lat2 = to.lat * radiansPerDegree
      var lon2 = to.lon * radiansPerDegree
      var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2))
      if (angle < 0) {
        angle += Math.PI * 2.0
      }
      angle = angle * degreesPerRadian // 角度
      return angle
    }
  }
  // 测量角度
  anglesFn() {
    var activeShapePoints = [] // 选中的点
    var activeShape
    var floatingPoint // 开始点
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    var that = this
    this.handler.setInputAction(function (event) {
      var cartesian = that.getCatesian3FromPX(event.position)
      if (Cesium.defined(cartesian)) {
        // 如果我们的鼠标不在地球上，地球位置将无法定义。
        if (activeShapePoints.length === 3) {
         
          that.label.style.display = 'none'
          handlerDestroy()
        }
        if (activeShapePoints.length === 0) {
          floatingPoint = that.createPoint(cartesian)
          activeShapePoints.push(cartesian)
          activeShape = new PolyLinePrimitive(activeShapePoints)
        }
        activeShapePoints.push(cartesian)
        that.createPoint(cartesian)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(function (event) {
      that.label.style.display = 'block'
      that.label.style.left = event.endPosition.x + 10 + 'px'
      that.label.style.top = event.endPosition.y + 15 + 'px'
      var cartesian = that.getCatesian3FromPX(event.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，绘制3个点结束'
        if (Cesium.defined(floatingPoint)) {
          floatingPoint.position.setValue(cartesian)
          activeShapePoints.pop()
          activeShapePoints.push(cartesian)
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    //重新绘制形状，使它不是动态的，并删除动态形状。
    function terminateShape() {
      // drawLine(activeShapePoints)
      new PolyLinePrimitive(activeShapePoints)
      that.viewer.entities.remove(activeShape)
      floatingPoint = undefined
      activeShape = undefined
    }
    function handlerDestroy() {
      let parentPointEntity = that.viewer.entities.add(new Cesium.Entity())
      terminateShape()
      that.viewer.entities.add({
        parent: parentPointEntity,
        name: '角度',
        position: activeShapePoints[1],
        label: {
          text: getAzimuthtAndCenter(activeShapePoints) + '°',
          font: '16px Helvetica',
          show: true,
          fillColor: Cesium.Color.RED,
          style: Cesium.LabelStyle.FILL, //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT, //水平位置
          // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          clampToGround: true,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          pixelOffset: new Cesium.Cartesian2(0, 20)
        }
      })
      // that.handler.destroy()
      that.destroy()
      activeShapePoints = []
    }

    function getAzimuthtAndCenter(points) {
      let a = Cesium.Cartesian3.distance(points[0], points[1])
      let b = Cesium.Cartesian3.distance(points[1], points[2])
      let c = Cesium.Cartesian3.distance(points[2], points[0])
      console.log(a)
      console.log(b)
      console.log(c)

      var cosA = (b * b + c * c - a * a) / (2 * b * c)
      var cosB = (a * a + c * c - b * b) / (2 * a * c)
      var cosC = (a * a + b * b - c * c) / (2 * a * b)

      // var A = (Math.acos(cosA) * 180) / Math.PI
      // var B = (Math.acos(cosB) * 180) / Math.PI
      var C = (Math.acos(cosC) * 180) / Math.PI
      return C
    }
  }
  // 三角测量
  measureTriangle(measureIndex) {
    var $this = this


    function getPositionDistance(positions) {
      let distance = 0
      for (let i = 0; i < positions.length - 1; i++) {
        let point1cartographic = $this.transformWGS84ToCartographic(positions[i])
        let point2cartographic = $this.transformWGS84ToCartographic(positions[i + 1])
        let geodesic = new Cesium.EllipsoidGeodesic()
        geodesic.setEndPoints(point1cartographic, point2cartographic)
        let s = geodesic.surfaceDistance
        s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2))
        distance = distance + s
      }
      return distance.toFixed(3)
    }

    function _getHeading(startPosition, endPosition) {
      if (!startPosition && !endPosition) return 0
      if (Cesium.Cartesian3.equals(startPosition, endPosition)) return 0
      let cartographic = Cesium.Cartographic.fromCartesian(startPosition)
      let cartographic2 = Cesium.Cartographic.fromCartesian(endPosition)
      return (cartographic2.height - cartographic.height).toFixed(2)
    }
    // 偏移点
    function _computesHorizontalLine(positions) {
      let cartographic = Cesium.Cartographic.fromCartesian(positions[0])
      let cartographic2 = Cesium.Cartographic.fromCartesian(positions[1])
      return Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic2.height)
    }
    var options = {}
    options.style = {
      width: 3,
      material: Cesium.Color.BLUE.withAlpha(0.5)
      // clampToGround: true,
      // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    }

    var _trianglesEntity = new Cesium.Entity(),
      _tempLineEntity = new Cesium.Entity(),
      _tempLineEntity2 = new Cesium.Entity(),
      _positions = [],
      _tempPoints = [],
      _tempPoints2 = []
    // _handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.handler.setInputAction(function (movement) {
      var position = $this.getCatesian3FromPX(movement.position)
      if (!position) return false
      if (_positions.length == 0) {
        _positions.push(position.clone())
        _positions.push(position.clone())
        _tempPoints.push(position.clone())
        _tempPoints.push(position.clone())
      } else {
        // $this.handler.destroy()
        $this.destroy()

        $this.label.style.display = 'none'
        measureIndex.value = null
        if (typeof options.callback === 'function') {
          options.callback({ e: _trianglesEntity, e2: _tempLineEntity, e3: _tempLineEntity2 })
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    // mouse
    $this.handler.setInputAction(function (movement) {
      $this.label.style.display = 'block'
      $this.label.style.left = movement.endPosition.x + 10 + 'px'
      $this.label.style.top = movement.endPosition.y + 15 + 'px'
      var position = $this.getCatesian3FromPX(movement.endPosition)
      if (!position) {
        $this.label.innerHTML = '超出地球范围'
        return false
      }
      $this.label.innerHTML = '左键添加点，再次左键结束'

      if (position && _positions.length > 0) {
        //直线
        _positions.pop()
        _positions.push(position.clone())
        let horizontalPosition = _computesHorizontalLine(_positions)
        //高度
        _tempPoints.pop()
        _tempPoints.push(horizontalPosition.clone())
        //水平线
        _tempPoints2.pop(), _tempPoints2.pop()
        _tempPoints2.push(position.clone())
        _tempPoints2.push(horizontalPosition.clone())
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    // create entity

    //直线
    _trianglesEntity.polyline = {
      positions: new Cesium.CallbackProperty(function () {
        return _positions
      }, false),
      ...options.style
    }
    _trianglesEntity.position = new Cesium.CallbackProperty(function () {
      return _positions[0]
    }, false)
    _trianglesEntity.point = {
      pixelSize: 5,
      outlineColor: Cesium.Color.BLUE,
      outlineWidth: 5
      // clampToGround: true,
      // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    }
    _trianglesEntity.label = {
      text: new Cesium.CallbackProperty(function () {
        return '直线:' + getPositionDistance($this.transformCartesianArrayToWGS84Array(_positions)) + '米'
      }, false),
      show: true,
      showBackground: true,
      font: '14px monospace',
      clampToGround: true,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(50, 10) //left top
    }
    //高度
    _tempLineEntity.polyline = {
      positions: new Cesium.CallbackProperty(function () {
        return _tempPoints
      }, false),
      ...options.style
    }
    _tempLineEntity.position = new Cesium.CallbackProperty(function () {
      return _tempPoints2[1]
    }, false)
    _tempLineEntity.point = {
      pixelSize: 5,
      outlineColor: Cesium.Color.BLUE,
      outlineWidth: 5
      // clampToGround: true,
      // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    }
    _tempLineEntity.label = {
      text: new Cesium.CallbackProperty(function () {
        return '高度:' + _getHeading(_tempPoints[0], _tempPoints[1]) + '米'
      }, false),
      show: true,
      // clampToGround: true,
      // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      showBackground: true,
      font: '14px monospace',
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(-20, 30) //left top
    }
    //水平
    _tempLineEntity2.polyline = {
      positions: new Cesium.CallbackProperty(function () {
        return _tempPoints2
      }, false),
      ...options.style
    }
    _tempLineEntity2.position = new Cesium.CallbackProperty(function () {
      return _positions[1]
    }, false)
    _tempLineEntity2.point = {
      pixelSize: 5,
      outlineColor: Cesium.Color.BLUE,
      outlineWidth: 5,
      clampToGround: true,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
    }
    _tempLineEntity2.label = {
      text: new Cesium.CallbackProperty(function () {
        return '水平距离:' + getPositionDistance($this.transformCartesianArrayToWGS84Array(_tempPoints2)) + '米'
      }, false),
      show: true,
      clampToGround: true,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      showBackground: true,
      font: '14px monospace',
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(-150, -20) //left top
    }
    this.viewer.entities.add(_tempLineEntity2)
    this.viewer.entities.add(_tempLineEntity)
    this.viewer.entities.add(_trianglesEntity)
  }

  transformCartesianToWGS84(cartesian) {
    var ellipsoid = Cesium.Ellipsoid.WGS84
    var cartographic = ellipsoid.cartesianToCartographic(cartesian)
    return {
      lng: Cesium.Math.toDegrees(cartographic.longitude),
      lat: Cesium.Math.toDegrees(cartographic.latitude),
      alt: cartographic.height
    }
  }

  transformWGS84ToCartesian(position, alt) {
    return position ? Cesium.Cartesian3.fromDegrees(position.lng || position.lon, position.lat, (position.alt = alt || position.alt), Cesium.Ellipsoid.WGS84) : Cesium.Cartesian3.ZERO
  }

  // getCatesian3FromPX(px) {
  //   // var picks = viewer.scene.pick(px)
  //   var picks = viewer.scene.drillPick(px)
  // console.log(picks);
  //   var cartesian = null
  //   var isOn3dtiles = false,
  //     isOnTerrain = false
  //   if (picks.primitive  instanceof Cesium.Cesium3DTileFeature) {
  //     console.log(333);
  //     //模型上拾取
  //     isOn3dtiles = true
  //   }
  //   // 3dtilset
  //   if (isOn3dtiles) {
  //     cartesian = viewer.scene.pickPosition(px)
  //     if (cartesian) {
  //       let cartographic = Cesium.Cartographic.fromCartesian(cartesian)
  //       if (cartographic.height < 0) cartographic.height = 0
  //       let lon = Cesium.Math.toDegrees(cartographic.longitude),
  //         lat = Cesium.Math.toDegrees(cartographic.latitude),
  //         height = cartographic.height //模型高度
  //       cartesian = this.transformWGS84ToCartesian({ lng: lon, lat: lat, alt: height })
  //     }
  //   }
  //   // 地形
  //   if (!picks && !viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider) {

  //     var ray = viewer.scene.camera.getPickRay(px)
  //     if (!ray) return null
  //     cartesian = viewer.scene.globe.pick(ray, viewer.scene)
  //     isOnTerrain = true
  //   }
  //   // 地球
  //   if (!isOn3dtiles && !isOnTerrain) {
  //     console.log('有地形');
  //     cartesian = viewer.scene.camera.pickEllipsoid(px, viewer.scene.globe.ellipsoid)
  //   }
  //   if (cartesian) {

  //     let position = this.transformCartesianToWGS84(cartesian)
  //     if (position.alt < 0) {
  //       cartesian = this.transformWGS84ToCartesian(position, 0.1)
  //     }
  //     return cartesian
  //   }
  //   return false

  // }

  getCatesian3FromPX(px) {
    if (this.viewer && px) {
      // var picks = this.viewer.scene.drillPick(px)
      var cartesian = null
      var isOn3dtiles = false,
        isOnTerrain = false
      // for (let i in picks) {
      //   let pick = picks[i]

      //   if ((pick && pick.primitive instanceof Cesium.Cesium3DTileFeature) || (pick && pick.primitive instanceof Cesium.Cesium3DTileset) || (pick && pick.primitive instanceof Cesium.Model)) {
      //     //模型上拾取
      //     isOn3dtiles = true
      //   }
      //   // 3dtilset
      //   if (isOn3dtiles) {
      //     this.viewer.scene.pick(px) // pick
      //     // cartesian = this.viewer.scene.pickPosition(px);
      //     var ray = this.viewer.camera.getPickRay(px)
      //     cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene)
      //     if (cartesian) {
      //       let cartographic = Cesium.Cartographic.fromCartesian(cartesian)

      //       if (cartographic.height < 0) cartographic.height = 0
      //       let lon = Cesium.Math.toDegrees(cartographic.longitude),
      //         lat = Cesium.Math.toDegrees(cartographic.latitude),
      //         height = cartographic.height
      //       cartesian = this.transformWGS84ToCartesian({ lng: lon, lat: lat, alt: height })
      //     }
      //   }
      // }
      // 地形
      let boolTerrain = this.viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider
      // Terrain
      if (!isOn3dtiles && !boolTerrain) {
        var ray = this.viewer.scene.camera.getPickRay(px)
        if (!ray) return null
        cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene)
        isOnTerrain = true
      }
      // 地球
      if (!isOn3dtiles && !isOnTerrain && boolTerrain) {
        cartesian = this.viewer.scene.camera.pickEllipsoid(px, this.viewer.scene.globe.ellipsoid)
      }
      if (cartesian) {
        let position = this.transformCartesianToWGS84(cartesian)
        if (position.alt < 0) {
          cartesian = this.transformWGS84ToCartesian(position, 0.1)
        }
        return cartesian
      }
      return false
    }
  }
  transformCartesianArrayToWGS84Array(cartesianArr) {
    var that = this
    return cartesianArr
      ? cartesianArr.map(function (item) {
        return that.transformCartesianToWGS84(item)
      })
      : []
  }
  transformWGS84ToCartographic(position) {
    return position ? Cesium.Cartographic.fromDegrees(position.lng || position.lon, position.lat, position.alt) : Cesium.Cartographic.ZERO
  }
  // 淹没分析
  createSubmergedAnalysis(options, measureIndex) {
    console.log(this.viewer.scene.globe.depthTestAgainstTerrain)
    var $this = this
    options = options || {}
    var _maxH = options.maxH || 15,
      _speed = options.speed || 1,
      _interval = options.interval || 10

    drawPolygonGraphics({
      height: 1,
      callback: function (polygon, polygonObj) {
        if (!$this.viewer.scene.globe.depthTestAgainstTerrain) {
          alert('请开启深度检测')
          return false
        }
        if (polygonObj) {
          setTimeout(() => {
            polygonObj.polygon.heightReference = 'CLAMP_TO_GROUND'
            polygonObj.polygon.material = new Cesium.Color.fromCssColorString('#3D81A5').withAlpha(0.7)
            var h = 0.0
            polygonObj.polygon.extrudedHeight = h
            var st = setInterval(function () {
              h = h + _speed
              if (h >= _maxH) {
                h = _maxH
                clearTimeout(st)
              }
              polygonObj.polygon.extrudedHeight = h
            }, _interval)
          }, 2000)
        }
      }
    })
    function drawPolygonGraphics(options) {
      // $this.handler.destroy()
      $this.destroy()
      $this.handler = new Cesium.ScreenSpaceEventHandler($this.viewer.scene.canvas)

      options = options || {}
      options.style = options.style || {
        width: 3,
        material: Cesium.Color.RED.withAlpha(0.8),
        clampToGround: true
      }

      var positions = [],
        polygon = new Cesium.PolygonHierarchy(),
        _polygonEntity = new Cesium.Entity(),
        polyObj = null,
        _label = ''
      $this.handler.setInputAction(function (movement) {
        var cartesian = $this.getCatesian3FromPX(movement.position)
        if (cartesian && cartesian.x) {
          if (positions.length == 0) {
            polygon.positions.push(cartesian.clone())
            positions.push(cartesian.clone())
          }
          positions.push(cartesian.clone())
          polygon.positions.push(cartesian.clone())

          if (!polyObj) create()
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
      // mouse
      $this.handler.setInputAction(function (movement) {
        var cartesian = $this.getCatesian3FromPX(movement.endPosition)
        if (positions.length >= 2) {
          if (cartesian && cartesian.x) {
            positions.pop()
            positions.push(cartesian)
            polygon.positions.pop()
            polygon.positions.push(cartesian)
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

      // right
      $this.handler.setInputAction(function (movement) {
        console.log(measureIndex.value)
        measureIndex.value = null
        // $this.handler.destroy()
        $this.destroy()

        positions.push(positions[0])

        if (typeof options.callback === 'function') {
          options.callback($this.transformCartesianArrayToWGS84Array(positions), polyObj)
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

      function create() {
        _polygonEntity.polyline = options.style

        _polygonEntity.polyline.positions = new Cesium.CallbackProperty(function () {
          return positions
        }, false)

        _polygonEntity.polygon = {
          hierarchy: new Cesium.CallbackProperty(function () {
            return polygon
          }, false),

          material: Cesium.Color.WHITE.withAlpha(0.1),
          clampToGround: options.clampToGround || false
        }
        _polygonEntity.clampToS3M = true

        polyObj = viewer.entities.add(_polygonEntity)
      }
    }
  }
  //折线
  foldLine(plottingIndex, callBack) {
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    // 取消双击事件-追踪该位置
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    var positions = []
    var poly = null
    var distance = 0
    var cartesian = null
    var floatingPoint
    let that = this
    this.handler.setInputAction(function (movement) {
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'
      var cartesian = that.getCatesian3FromPX(movement.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
        if (positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    that.handler.setInputAction(movement => {
      var cartesian = that.getCatesian3FromPX(movement.position)
      if (Cesium.defined(cartesian)) {
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        positions.push(cartesian)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(function (movement) {
      // that.handler.destroy() // 关闭事件句柄
      that.destroy()
      positions.pop() // 最后一个点无效
      that.label.style.display = 'none'
      plottingIndex.value = null
      if (callBack) {
        let s = []
        positions.forEach(v => {
          var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(v) //cesium函数转换至地理数据类型的经纬度55555

          var coords = '经度：' + Cesium.Math.toDegrees(cartographic.longitude).toFixed(4) + '，纬度：' + Cesium.Math.toDegrees(cartographic.latitude).toFixed(4) + '，相机高度：' + Math.ceil(this.viewer.camera.positionCartographic.height)

          s.push(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude))

        })



        callBack(s)
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  // 添加标记
  addMark(text, plottingIndex) {
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    var measureFeature_line = []
    // 取消双击事件-追踪该位置
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    // handler = new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection)

    var positions = []
    var poly = null
    var distance = 0
    var cartesian = null
    var floatingPoint
    let that = this
    this.handler.setInputAction(function (movement) {
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'

      var cartesian = that.getCatesian3FromPX(movement.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    that.handler.setInputAction(movement => {
      var cartesian = that.getCatesian3FromPX(movement.position)
      if (Cesium.defined(cartesian)) {
        that.viewer.entities.add({
          position: cartesian,
          billboard: {
            image: '/mark.png',
            show: true, // default
            scale: 2.0, // default: 1.0
            width: 25, // default: undefined
            height: 25, // default: undefined
            // clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          },
          label: {
            text: text,
            font: '30px sans-serif',
            fillColor: Cesium.Color.RED,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            pixelOffset: new Cesium.Cartesian2(24, 20)
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          }
        })
        // that.handler.destroy() // 关闭事件句柄
        that.destroy()
        that.label.style.display = 'none'
        plottingIndex.value = null
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (movement) {
      // that.handler.destroy() // 关闭事件句柄
      that.destroy()
      that.label.style.display = 'none'
      plottingIndex.value = null
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  //开始绘制 多边形
  hzdbx(drawRectangleCallBack, num, measureIndex) {
    // this.handler.destroy()
    this.destroy()
    var $this = this
    var that = this
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    // 鼠标事件
    var positions = []
    var tempPoints = []
    var polygon = null
    this.handler.setInputAction(function (movement) {
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'
      var cartesian = that.getCatesian3FromPX(movement.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(function (movement) {
      var cartesian = that.getCatesian3FromPX(movement.position)
      console.log(cartesian)
      if (Cesium.defined(cartesian)) {
        console.log('ifffffff')
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        positions.push(cartesian)
        that.createPoint(cartesian)
        // 在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1])
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
        var heightString = cartographic.height
        tempPoints.push({
          lon: longitudeString,
          lat: latitudeString,
          hei: heightString
        })
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(movement => {
      // this.handler.destroy()/
      this.destroy()
      positions.pop()
      drawRectangleCallBack(positions)
      that.label.style.display = 'none'
      measureIndex.value = null
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  //集结地
  jjstartCreate(plottingIndex) {
    //加载集结地
    function loadGatheringPlace(data, $this) {
      $this.lonLatArr = []
      if (data.length < 2) {
        return null
      }
      var length = data.length
      var p1 = data[0]
      var p2 = data[length - 1]
      var firstPoint = $this.cartesianToLatlng(p1)
      var endPoints = $this.cartesianToLatlng(p2)
      $this.lonLatArr.push(...firstPoint, ...endPoints)
      var gatheringPlace = []
      var res = fineGatheringPlace(firstPoint, endPoints, data, $this)
      for (var i = 0; i < res.length; i++) {
        var cart3 = new Cesium.Cartesian3(res[i].x, res[i].y, res[i].z)
        gatheringPlace.push(cart3)
      }
      var gatheringPlaceEntity = $this.viewer.entities.add({
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(gatheringPlace),
          show: true,
          fill: true,
          clampToGround: true,
          material: Cesium.Color.AQUA.withAlpha(0.5)
        }
      })
      return gatheringPlaceEntity
    }
    //创建集结地
    function createGatheringPlace($this) {
      var gatheringPlaceEntity = $this.viewer.entities.add({
        polygon: {
          hierarchy: new Cesium.CallbackProperty(function () {
            // return new Cesium.PolygonHierarchy($this._positions);
            var length = $this._positions.length
            var p1 = $this._positions[0]
            var p2 = $this._positions[length - 1]
            var firstPoint = $this.cartesianToLatlng(p1)
            var endPoints = $this.cartesianToLatlng(p2)
            var gatheringPlace = []
            var res = fineGatheringPlace(firstPoint, endPoints, $this._positions, $this)
            for (var i = 0; i < res.length; i++) {
              var cart3 = new Cesium.Cartesian3(res[i].x, res[i].y, res[i].z)
              gatheringPlace.push(cart3)
            }
            return new Cesium.PolygonHierarchy(gatheringPlace)
          }, false),
          show: true,
          fill: true,
          clampToGround: true,
          material: Cesium.Color.AQUA.withAlpha(0.5)
        }
      })
      $this._entities_gatheringPlace.push(gatheringPlaceEntity)
      return gatheringPlaceEntity
    }

    function cartesianToLatlng(cartesian) {
      var latlng = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
      var lat = Cesium.Math.toDegrees(latlng.latitude)
      var lng = Cesium.Math.toDegrees(latlng.longitude)

      return [lng, lat]
    }

    //求集结地插值坐标
    function fineGatheringPlace(tailPoint, headerPoint, data, $this) {
      let points = data.length
      if (points < 2) {
        return false
      } else {
        let pnts = new Array()

        data.forEach(function (item) {
          pnts.push($this.cartesianToLatlng(item))
        })

        if (pnts.length === 2) {
          let mid = utils.Mid(pnts[0], pnts[1])
          let d = utils.MathDistance(pnts[0], mid) / 0.9
          let pnt = utils.getThirdPoint(pnts[0], mid, Constants.HALF_PI, d, true)
          pnts = [pnts[0], pnt, pnts[1]]
        }
        let mid = utils.Mid(pnts[0], pnts[2])
        pnts.push(mid, pnts[0], pnts[1])

        let [normals, pnt1, pnt2, pnt3, pList] = [[], undefined, undefined, undefined, []]
        for (let i = 0; i < pnts.length - 2; i++) {
          pnt1 = pnts[i]
          pnt2 = pnts[i + 1]
          pnt3 = pnts[i + 2]
          let normalPoints = utils.getBisectorNormals($this.t, pnt1, pnt2, pnt3)
          normals = normals.concat(normalPoints)
        }
        let count = normals.length
        normals = [normals[count - 1]].concat(normals.slice(0, count - 1))
        for (let i = 0; i < pnts.length - 2; i++) {
          pnt1 = pnts[i]
          pnt2 = pnts[i + 1]
          pList = pList.concat(pnt1)
          for (let t = 0; t <= Constants.FITTING_COUNT; t++) {
            let pnt = utils.getCubicValue(t / Constants.FITTING_COUNT, pnt1, normals[i * 2], normals[i * 2 + 1], pnt2)

            pList = pList.concat(pnt)
          }
          pList = pList.concat(pnt2)
        }
        return Cesium.Cartesian3.fromDegreesArray(pList)
      }
    }
    var $this = this
    var that = this
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.handler.setInputAction(function (evt) {
      //单机开始绘制
      //屏幕坐标转地形上坐标
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (Cesium.defined(cartesian)) {
        if ($this._positions.length == 0) {
          $this._positions.push(cartesian.clone())
          $this.floatingPoint = $this.createPoint(cartesian)
        }
        if ($this._positions.length <= 2) {
          $this.createPoint(cartesian) // 绘制点
          $this._positions.push(cartesian)
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (evt) {
      that.label.style.display = 'block'
      that.label.style.left = evt.endPosition.x + 10 + 'px'
      that.label.style.top = evt.endPosition.y + 15 + 'px'
      var cartesian = $this.getCatesian3FromPX(evt.endPosition)
      if (Cesium.defined(cartesian)) {
        that.label.innerHTML = '左键添加点，右键结束'
        //移动时绘制面
        if ($this._positions.length < 2) return
        var cartesian = $this.getCatesian3FromPX(evt.endPosition)

        if (!Cesium.defined($this._gatheringPlace)) {
          $this._gatheringPlace = createGatheringPlace($this)
        }
        $this.floatingPoint.position.setValue(cartesian)
        if ($this._gatheringPlace) {
          $this._positions.pop()
          $this._positions.push(cartesian)
        }
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    this.handler.setInputAction(function (evt) {
      // debugger
      if (!$this._gatheringPlace) return
      var cartesian = $this.getCatesian3FromPX(evt.position)
      $this._positions.pop()
      $this._positions.push(cartesian)
      $this._gatheringPlaceData = $this._positions.concat()
      $this.viewer.entities.remove($this._gatheringPlace) //移除

      var gatheringPlace = loadGatheringPlace($this._gatheringPlaceData, $this) //加载
      $this._gatheringPlace = null
      $this._positions = []
      $this.floatingPoint.position.setValue(cartesian)
      $this._entities_gatheringPlace.push(gatheringPlace)
      $this._gatheringPlaceLast = gatheringPlace
      // $this.clearPoint();
      $this.destroy()
      // $this.getData()
      $this.clear()
      $this.label.style.display = 'none'
      plottingIndex.value = null
      // $this.callBack($this.lonLatArr)
      // return  $this.getData()
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  // 画圆
  drawCircle(callback, plottingIndex) {
    // this.handler.destroy()
    this.destroy()

    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    let that = this
    var circle_center_entity = null // 圆心点 entity
    var temporary_circle_entity = null // 临时圆形entity
    var circle_entity = null // 结果圆形entity
    var circle_end_point = null // 结束点
    var circle_center_point = null // 圆心点

    function click_draw_circle() {
      // 再次点击的时候，清除已绘制的中心点，临时圆和结果圆，初始化参数
      if (circle_entity !== null) {
        that.viewer.entities.remove(circle_center_entity)
        that.viewer.entities.remove(temporary_circle_entity)
        that.viewer.entities.remove(circle_entity)
        circle_center_entity = null
        temporary_circle_entity = null
        circle_entity = null
        circle_end_point = null
        circle_center_point = null
      }

      // handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      that.handler.setInputAction(event => {
        that.label.style.display = 'block'
        that.label.style.left = event.endPosition.x + 10 + 'px'
        that.label.style.top = event.endPosition.y + 15 + 'px'
        const ray = that.viewer.camera.getPickRay(event.endPosition)


        var position1
        var cartographic
        // if (ray) {
        //   position1 = that.viewer.scene.globe.pick(ray, that.viewer.scene)
        //   console.log(position1);
        // }
        // if (position1) {
        //   cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position1)
        // }

        var cartesian = that.getCatesian3FromPX(event.endPosition)
        console.log(cartesian);

        if (Cesium.defined(cartesian)) {
          that.label.innerHTML = '左键添加点，再次左键结束'
          let ellipsoid = that.viewer.scene.globe.ellipsoid
          let cartographic = ellipsoid.cartesianToCartographic(cartesian)
          let lon = Cesium.Math.toDegrees(cartographic.longitude) // 经度
          let lat = Cesium.Math.toDegrees(cartographic.latitude) // 纬度
          console.log(lon, lat);
          if (temporary_circle_entity) {
            // 修改结束点-用于动态绘制圆形
            circle_end_point = {
              lon: lon,
              lat: lat,
              height: 0
            }
          }
        } else {
          that.label.innerHTML = '超出地球范围'
        }
        // if (cartographic) {
        //   that.label.innerHTML = '左键添加点，再次左键结束'
        //   // 屏幕坐标转为世界坐标
        //   let cartesian = that.viewer.scene.globe.pick(that.viewer.camera.getPickRay(event.endPosition), that.viewer.scene)
        //   let ellipsoid = that.viewer.scene.globe.ellipsoid
        //   let cartographic = ellipsoid.cartesianToCartographic(cartesian)
        //   let lon = Cesium.Math.toDegrees(cartographic.longitude) // 经度
        //   let lat = Cesium.Math.toDegrees(cartographic.latitude) // 纬度
        //   if (temporary_circle_entity) {
        //     // 修改结束点-用于动态绘制圆形
        //     circle_end_point = {
        //       lon: lon,
        //       lat: lat,
        //       height: 0
        //     }
        //   }
        // } else {
        //   that.label.innerHTML = '超出地球范围'
        // }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

      // 鼠标点击左键
      that.handler.setInputAction(event => {
        // 屏幕坐标转为世界坐标
        // let cartesian = that.viewer.scene.globe.pick(that.viewer.camera.getPickRay(event.position), that.viewer.scene)
        // let ellipsoid = that.viewer.scene.globe.ellipsoid
        // let cartographic = ellipsoid.cartesianToCartographic(cartesian)
        // let lon = Cesium.Math.toDegrees(cartographic.longitude) // 经度
        // let lat = Cesium.Math.toDegrees(cartographic.latitude) // 纬度
        var cartesian = that.getCatesian3FromPX(event.position)

        let ellipsoid = that.viewer.scene.globe.ellipsoid
        let cartographic = ellipsoid.cartesianToCartographic(cartesian)
        let lon = Cesium.Math.toDegrees(cartographic.longitude) // 经度
        let lat = Cesium.Math.toDegrees(cartographic.latitude) // 纬度

        // 判断圆心是否已经绘制，如果绘制了，再次点击左键的时候，就是绘制最终结果圆形
        if (circle_center_entity) {

          // 设置最终点
          circle_end_point = {
            lon: lon,
            lat: lat,
            height: 0
          }
          // 绘制结果多边形
          draw_circle()
          callback({ lon: circle_center_point.lon, lat: circle_center_point.lat, semiMinorAxis: two_points_distance(circle_center_point, circle_end_point), en: circle_entity })

          // 清除事件
          that.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
          that.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
          // 清除 绘制的中心点和临时圆
          that.viewer.entities.remove(circle_center_entity)
          that.viewer.entities.remove(temporary_circle_entity)
          that.label.style.display = 'none'
          plottingIndex.value = null
        } else {
          // 设置中心点坐标和结束点坐标
          circle_end_point = circle_center_point = {
            lon: lon,
            lat: lat,
            height: 0
          }

          // 绘制圆心点
          create_circle_center_point([lon, lat])
          // 开始绘制动态圆形
          draw_dynamic_circle(circle_center_point)
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }

    // 创建圆心点
    function create_circle_center_point(point_arr) {
      console.log(point_arr);
      circle_center_entity = that.viewer.entities.add({
        // fromDegrees（经度，纬度，高度）以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(point_arr[0], point_arr[1], 100),
        point: {
          // 点的大小（像素）
          pixelSize: 5,
          // 点位颜色，fromCssColorString 可以直接使用CSS颜色
          color: Cesium.Color.WHITE,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          // 边框颜色
          outlineColor: Cesium.Color.fromCssColorString('#fff'),
          // 边框宽度(像素)
          outlineWidth: 2,
          // 是否显示
          show: true
        }
      })
    }

    // 绘制动态圆
    function draw_dynamic_circle(point) {
      console.log(two_points_distance(point, circle_end_point));
      temporary_circle_entity = that.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(point.lon, point.lat, point.height),
        ellipse: {
          // 半短轴（画圆：半短轴和半长轴一致即可） start_point 
          semiMinorAxis: new Cesium.CallbackProperty(() => {

            // PolygonHierarchy 定义多边形及其孔的线性环的层次结构（空间坐标数组）
            // return two_points_distance(point, circle_end_point)
            return two_points_distance(point, circle_end_point) == 0 ? 1 : two_points_distance(point, circle_end_point)

          }, false),
          // 半长轴
          semiMajorAxis: new Cesium.CallbackProperty(() => {
            // PolygonHierarchy 定义多边形及其孔的线性环的层次结构（空间坐标数组）
            // return two_points_distance(point, circle_end_point)
            return two_points_distance(point, circle_end_point) == 0 ? 1 : two_points_distance(point, circle_end_point)
          }, false),
          // 填充色
          material: Cesium.Color.RED.withAlpha(0.5),
          // 是否有边框
          outline: true,
          // 边框颜色
          outlineColor: Cesium.Color.BLUE,
          // 边框宽度
          outlineWidth: 4
        }
      })
    }

    // 绘制结果圆形
    function draw_circle() {
      circle_entity = that.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(circle_center_point.lon, circle_center_point.lat),
        ellipse: {
          // 半短轴（画圆：半短轴和半长轴一致即可）
          semiMinorAxis: two_points_distance(circle_center_point, circle_end_point),
          // 半长轴
          semiMajorAxis: two_points_distance(circle_center_point, circle_end_point),
          // 填充色
          // material: Cesium.Color.RED.withAlpha(0),
          material: Cesium.Color.RED.withAlpha(0.5),
          // 是否有边框
          // outline: true,
          // // 边框颜色
          // height: 1.0,
          // // heightReference: 100000.0,
          // // numberOfVerticalLines: 100000,
          // outlineColor: Cesium.Color.BLUE,

          // extrudedHeight: 0.0,
          // // 边框宽度
          // outlineWidth: 4
          material: Cesium.Color.RED.withAlpha(0.5),
          // 是否有边框
          outline: true,
          // 边框颜色
          outlineColor: Cesium.Color.BLUE,
          // 边框宽度
          outlineWidth: 4
        }
      })
      // drawCircleCallBack({lon:circle_center_point.lon, lat:circle_center_point.lat,semiMinorAxis:two_points_distance(circle_center_point, circle_end_point),en:circle_entity})
    }

    // 根据经纬度计算两点之前的直线距离
    function two_points_distance(start_point, end_point) {
      // 经纬度转换为世界坐标
      var start_position = Cesium.Cartesian3.fromDegrees(start_point.lon, start_point.lat, start_point.height)
      var end_position = Cesium.Cartesian3.fromDegrees(end_point.lon, end_point.lat, end_point.height)
      // 返回两个坐标的距离（单位：米）
      return Cesium.Cartesian3.distance(start_position, end_position)
    }
    click_draw_circle()
  }
  // 矩形

  drawRectangle(drawRectangleCallBack, plottingIndex) {
    // this.handler.destroy()
    this.destroy()

    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    let that = this
    let clickPoint = []
    var move, ding
    // return new Promise((resolve, reject) => {
    // 鼠标左键绘制
    that.handler.setInputAction(function (movement) {
      const earthPosition = that.viewer.camera.pickEllipsoid(movement.position, that.viewer.scene.globe.ellipsoid) //当前世界坐标笛卡尔积
      if (Cesium.defined(earthPosition)) {
        // 判断现在是第几个点
        if (clickPoint.length === 0) {
          //还没有点，添加第一个点
          clickPoint.push(earthPosition)
        } else {
          //绘制矩形
          clickPoint.push(earthPosition)
          that.label.style.display = 'none'
          // 绘制矩形
          const rectangleHand = Cesium.Rectangle.fromCartesianArray(clickPoint)
          ding = that.viewer.entities.add({
            name: 'drawRectangle',
            // id:'11111',
            rectangle: {
              coordinates: rectangleHand,
              material: Cesium.Color.fromCssColorString('rgba(25, 98, 134, 0.5)')
            }
          })
          // 删除移动矩形
          // viewer.entities.removeEntityByName('moveDrawRectangle')
          // viewer.entities.remove(viewer.entities.getById('222'))
          that.viewer.entities.remove(move)
          const northwest = Cesium.Rectangle.northwest(rectangleHand) //西北角弧度坐标（左上）
          const southwest = Cesium.Rectangle.southwest(rectangleHand) //西南角弧度坐标（左下）
          const northeast = Cesium.Rectangle.northeast(rectangleHand) //东北角弧度坐标（右上）
          const southeast = Cesium.Rectangle.southeast(rectangleHand) //东南角弧度坐标（右下）

          // 转换为经纬度
          const leftTop = [Cesium.Math.toDegrees(northwest.longitude), Cesium.Math.toDegrees(northwest.latitude)] //左上角经度
          const leftBottom = [Cesium.Math.toDegrees(southwest.longitude), Cesium.Math.toDegrees(southwest.latitude)] //左下角经度
          const rightTop = [Cesium.Math.toDegrees(northeast.longitude), Cesium.Math.toDegrees(northeast.latitude)] //右上角经度
          const rightBottom = [Cesium.Math.toDegrees(southeast.longitude), Cesium.Math.toDegrees(southeast.latitude)] //右下角经度
          var polygon = turf.polygon([[leftTop, rightTop, rightBottom, leftBottom, leftTop]])

          // 面积(m²)
          var area = turf.area(polygon)
          const data = {
            leftTop: leftTop,
            leftBottom: leftBottom,
            rightTop: rightTop,
            rightBottom: rightBottom,
            area
          }
          // resolve(data)
          drawRectangleCallBack(data)
          clickPoint = [] //清空
          that.viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE) //停止监听移动事件
          that.viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) //停止监听移动事件
          // that.handler.destroy()
          that.destroy()
          plottingIndex.value = null
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    that.handler.setInputAction(function (movement) {
      that.label.style.display = 'block'
      that.label.style.left = movement.endPosition.x + 10 + 'px'
      that.label.style.top = movement.endPosition.y + 15 + 'px'
      const newPosition = that.viewer.camera.pickEllipsoid(movement.endPosition, that.viewer.scene.globe.ellipsoid) //当前世界坐标笛卡尔积
      if (Cesium.defined(newPosition)) {
        that.label.innerHTML = '左键添加点，再次左键结束'
        const movePoint = [...clickPoint, newPosition]
        // viewer.entities.removeEntityByName('moveDrawRectangle')
        // viewer.entities.remove(viewer.entities.getById('222'))
        that.viewer.entities.remove(move)
        const rectangleHand = {
          coordinates: new Cesium.CallbackProperty(function () {
            const obj = Cesium.Rectangle.fromCartesianArray(movePoint)
            return obj
          }, false),
          material: Cesium.Color.fromCssColorString('rgba(198, 27, 27, 0.48)')
        }
        move = that.viewer.entities.add({
          // id:'222',
          name: 'moveDrawRectangle',
          rectangle: rectangleHand
        })
      } else {
        that.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    // })
  }
  //创建点 createPoint
  createPoint(cartesian) {
    var $this = this
    var point = this.viewer.entities.add({
      position: cartesian,
      point: {
        pixelSize: 10,
        color: Cesium.Color.YELLOW,
        clampToGround: true,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    })
    $this._entities_point.push(point)
    return point
  }
  // 创建标记

  createBillboard(cartesian) {
    let pinBuilder = new Cesium.PinBuilder()
    var $this = this
    var point = this.viewer.entities.add({
      position: cartesian,
      billboard: {
        image: '/img/mark-blue.png',
        width: 25, // default: undefined
        height: 25, // default: undefined
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,

      },
    })
    $this._entities_billboard.push(point)
    return point
  }

  clearBillboard() {
    for (var i = 0; i < this._entities_billboard.length; i++) {
      this.viewer.entities.remove(this._entities_billboard[i])
    }
    this._entities_billboard = [] //脏数据
  }

  //销毁事件
  destroy() {

    if (this.handler) {

      this.handler.destroy()
      this.label.style.display = 'none'
      this.handler = null
    }
  }

  /*
  绘制直线箭头
   */

  //加载箭头
  loadStraightArrow(data) {
    var $this = this
    if (data.length < 2) {
      return null
    }
    var length = data.length
    var p1 = data[0]
    var p2 = data[length - 1]
    var firstPoint = $this.cartesianToLatlng(p1)
    var endPoints = $this.cartesianToLatlng(p2)
    var arrow = []
    var res = $this.fineArrow([firstPoint[0], firstPoint[1]], [endPoints[0], endPoints[1]])
    for (var i = 0; i < res.length; i++) {
      var cart3 = new Cesium.Cartesian3(res[i].x, res[i].y, res[i].z)
      arrow.push(cart3)
    }
    var arrowEntity = $this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(arrow),
        show: true,
        fill: true,
        clampToGround: true,
        material: Cesium.Color.AQUA.withAlpha(0.5)
      }
    })
    return arrowEntity
  }

  //开始创建
  zxjtstartCreate(plottingIndex) {
    // this.handler.destroy()
    this.destroy()
    var $this = this
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.handler.setInputAction(function (evt) {
      //单机开始绘制
      //屏幕坐标转地形上坐标
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if ($this._positions.length == 0) {
        $this._positions.push(cartesian.clone())
        $this.floatingPoint = $this.createPoint(cartesian)
      }
      if (!$this._straightArrow) {
        $this.createPoint(cartesian) // 绘制点
      }
      $this._positions.push(cartesian)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (evt) {
      $this.label.style.display = 'block'
      $this.label.style.left = evt.endPosition.x + 10 + 'px'
      $this.label.style.top = evt.endPosition.y + 15 + 'px'
      var cartesian = $this.getCatesian3FromPX(evt.endPosition)
      if (Cesium.defined(cartesian)) {
        $this.label.innerHTML = '左键添加点，右键结束'
        //移动时绘制面
        if ($this._positions.length < 2) return
        if (!Cesium.defined($this._straightArrow)) {
          $this._straightArrow = $this.createStraightArrow()
        }
        $this.floatingPoint.position.setValue(cartesian)
        if ($this._straightArrow) {
          $this._positions.pop()
          $this._positions.push(cartesian)
        }
      } else {
        $this.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    this.handler.setInputAction(function (evt) {
      if (!$this._straightArrow) return
      var cartesian = $this.getCatesian3FromPX(evt.position)
      // $this._positions.pop()
      $this._positions.push(cartesian)
      $this._straightArrowData = $this._positions.concat()
      $this.viewer.entities.remove($this._straightArrow) //移除
      $this._straightArrow = null
      $this._positions = []
      $this.floatingPoint.position.setValue(cartesian)
      var straightArrow = $this.loadStraightArrow($this._straightArrowData) //加载
      $this._entities_straightArrow.push(straightArrow)
      $this._straightArrowLast = straightArrow
      $this.clearPoint()
      // $this.handler.destroy()
      $this.destroy()
      plottingIndex.value = null
      $this.label.style.display = 'none'
      // $this.handler = null
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  //创建直线箭头
  createStraightArrow() {
    var $this = this
    var arrowEntity = $this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(function () {
          // return new Cesium.PolygonHierarchy($this._positions);
          var length = $this._positions.length
          var p1 = $this._positions[0]
          var p2 = $this._positions[length - 1]
          var firstPoint = $this.cartesianToLatlng(p1)
          var endPoints = $this.cartesianToLatlng(p2)
          var arrow = []
          var res = $this.fineArrow([firstPoint[0], firstPoint[1]], [endPoints[0], endPoints[1]])
          for (var i = 0; i < res.length; i++) {
            var cart3 = new Cesium.Cartesian3(res[i].x, res[i].y, res[i].z)
            arrow.push(cart3)
          }
          return new Cesium.PolygonHierarchy(arrow)
        }, false),
        show: true,
        fill: true,
        clampToGround: true,
        material: Cesium.Color.AQUA.withAlpha(0.5)
      }
    })
    $this._entities_straightArrow.push(arrowEntity)
    return arrowEntity
  }

  cartesianToLatlng(cartesian) {
    var latlng = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
    var lat = Cesium.Math.toDegrees(latlng.latitude)
    var lng = Cesium.Math.toDegrees(latlng.longitude)

    return [lng, lat]
  }
  clearPoint() {
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.entities.remove(this._entities_point[i])
    }
    this._entities_point = [] //脏数据
  }

  //清空实体对象
  clear() {
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.entities.remove(this._entities_point[i])
    }
    for (var i = 0; i < this._entities_straightArrow.length; i++) {
      this.viewer.entities.remove(this._entities_straightArrow[i])
    }

    this.floatingPoint = null //标识点
    this._straightArrow = null //活动箭头
    this._straightArrowLast = null //最后一个箭头
    this._positions = [] //活动点
    this._entities_point = [] //脏数据
    this._entities_straightArrow = [] //脏数据
    this._straightArrowData = null //用于构造箭头数据
  }

  // 求取箭头坐标函数/
  //箭头配置函数
  fineArrowDefualParam() {
    return {
      tailWidthFactor: 0.15,
      neckWidthFactor: 0.2,
      headWidthFactor: 0.25,
      headAngle: Math.PI / 8.5,
      neckAngle: Math.PI / 13
    }
  }

  fineArrow(tailPoint, headerPoint) {
    var $this = this
    if (tailPoint.length < 2 || headerPoint.length < 2) return
    //画箭头的函数
    let tailWidthFactor = $this.fineArrowDefualParam().tailWidthFactor
    let neckWidthFactor = $this.fineArrowDefualParam().neckWidthFactor
    let headWidthFactor = $this.fineArrowDefualParam().headWidthFactor
    let headAngle = $this.fineArrowDefualParam().headAngle
    let neckAngle = $this.fineArrowDefualParam().neckAngle
    var o = []
    o[0] = tailPoint
    o[1] = headerPoint
    var e = o[0],
      r = o[1],
      n = $this.getBaseLength(o),
      g = n * tailWidthFactor,
      //尾部宽度因子
      i = n * neckWidthFactor,
      //脖子宽度银子
      s = n * headWidthFactor,
      //头部宽度因子
      a = $this.getThirdPoint(r, e, Math.PI / 2, g, !0),
      l = $this.getThirdPoint(r, e, Math.PI / 2, g, !1),
      u = $this.getThirdPoint(e, r, headAngle, s, !1),
      c = $this.getThirdPoint(e, r, headAngle, s, !0),
      p = $this.getThirdPoint(e, r, neckAngle, i, !1),
      h = $this.getThirdPoint(e, r, neckAngle, i, !0),
      d = []
    d.push(a[0], a[1], p[0], p[1], u[0], u[1], r[0], r[1], c[0], c[1], h[0], h[1], l[0], l[1], e[0], e[1])
    return Cesium.Cartesian3.fromDegreesArray(d)
  }

  getBaseLength(t) {
    return Math.pow(this.wholeDistance(t), 0.99)
  }

  wholeDistance(t) {
    for (var o = 0, e = 0; e < t.length - 1; e++) o += this.distance(t[e], t[e + 1])
    return o
  }

  distance(t, o) {
    return Math.sqrt(Math.pow(t[0] - o[0], 2) + Math.pow(t[1] - o[1], 2))
  }

  getThirdPoint(t, o, e, r, n) {
    var g = this.getAzimuth(t, o),
      i = n ? g + e : g - e,
      s = r * Math.cos(i),
      a = r * Math.sin(i)
    return [o[0] + s, o[1] + a]
  }

  getAzimuth(t, o) {
    var e,
      r = Math.asin(Math.abs(o[1] - t[1]) / this.distance(t, o))
    return o[1] >= t[1] && o[0] >= t[0] ? (e = r + Math.PI) : o[1] >= t[1] && o[0] < t[0] ? (e = 2 * Math.PI - r) : o[1] < t[1] && o[0] < t[0] ? (e = r) : o[1] < t[1] && o[0] >= t[0] && (e = Math.PI - r), e
  }

  //燕尾箭头

  gjstartDraw(plottingIndex) {
    var $this = this
    this.state = 1
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.handler.setInputAction(function (evt) {
      //单机开始绘制
      var cartesian
      cartesian = $this.getCatesian3FromPX(evt.position, $this.viewer)
      if (!cartesian) return
      // var ray = viewer.camera.getPickRay(evt.position);
      // if (!ray) return;
      // var cartesian = viewer.scene.globe.pick(ray, $this.viewer.scene);
      if ($this.positions.length == 0) {
        $this.floatPoint = $this.createPoint(cartesian, $this.viewer)
        $this.floatPoint.wz = -1
      }
      $this.positions.push(cartesian)
      var point = $this.createPoint(cartesian)
      if ($this.positions.length > 2) {
        point.wz = $this.positions.length - 1 //点对应的在positions中的位置  屏蔽mouseMove里往postions添加时 未创建点
      } else {
        point.wz = $this.positions.length //点对应的在positions中的位置
      }
      $this.pointArr.push(point)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (evt) {
      //移动时绘制面
      $this.label.style.display = 'block'
      $this.label.style.left = evt.endPosition.x + 10 + 'px'
      $this.label.style.top = evt.endPosition.y + 15 + 'px'
      const newPosition = $this.viewer.camera.pickEllipsoid(evt.endPosition, $this.viewer.scene.globe.ellipsoid)

      if (Cesium.defined(newPosition)) {
        $this.label.innerHTML = '左键添加点，右键结束'
        if ($this.positions.length < 2) return

        var cartesian
        cartesian = $this.getCatesian3FromPX(evt.endPosition, $this.viewer)
        if (!cartesian) return
        $this.floatPoint.position.setValue(cartesian)
        if ($this.positions.length >= 2) {
          if (!Cesium.defined($this.arrowEntity)) {
            $this.positions.push(cartesian)
            $this.arrowEntity = $this.showArrowOnMap($this.positions)
            $this.arrowEntity.objId = $this.objId
          } else {
            $this.positions.pop()
            $this.positions.push(cartesian)
          }
        }
      } else {
        $this.label.innerHTML = '超出地球范围'
      }

      // const ray = that.viewer.camera.getPickRay(evt.endPosition)
      // var position1
      // var cartographic
      // if (ray) {
      //   position1 = that.viewer.scene.globe.pick(ray, that.viewer.scene)
      // }
      // if (position1) {
      //   cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position1)
      // }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(function (evt) {
      //右击结束绘制
      // var ray = viewer.camera.getPickRay(evt.position);
      // if (!ray) return;
      // var cartesian = viewer.scene.globe.pick(ray, $this.viewer.scene);
      var cartesian
      cartesian = $this.getCatesian3FromPX(evt.position, $this.viewer)
      if (!cartesian) return
      for (var i = 0; i < $this.pointArr.length; i++) {
        $this.pointArr[i].show = false
      }
      $this.floatPoint.show = false
      $this.viewer.entities.remove($this.floatPoint)
      $this.floatPoint = null
      var point = $this.createPoint(cartesian)
      point.show = false
      point.wz = $this.positions.length
      $this.pointArr.push(point)
      // $this.handler.destroy()
      $this.destroy()
      $this.positions = []
      $this.arrowEntity = null
      $this.label.style.display = 'none'
      plottingIndex.value = null
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  showArrowOnMap(positions) {
    var $this = this
    var update = function () {
      //计算面
      if (positions.length < 3) {
        return null
      }
      var lnglatArr = []
      for (var i = 0; i < positions.length; i++) {
        var lnglat = $this.cartesianToLatlng(positions[i])
        lnglatArr.push(lnglat)
      }
      var res = xp.algorithm.tailedAttackArrow(lnglatArr)
      var index = JSON.stringify(res.polygonalPoint).indexOf('null')
      var returnData = []
      if (index == -1) returnData = res.polygonalPoint
      return new Cesium.PolygonHierarchy(returnData)
    }
    return this.viewer.entities.add({
      polygon: new Cesium.PolygonGraphics({
        hierarchy: new Cesium.CallbackProperty(update, false),
        show: true,
        fill: true,
        material: $this.fillMaterial
      })
    })
  }

  // 钳击箭头

  PincerArrow() {
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    var $this = this
    this.state = 1
    this.handler.setInputAction(function (movement) {
      if ($this.floatPoint) {
        //移除动态点
        $this.floatPoint.show = false
        $this.viewer.entities.remove($this.floatPoint)
        $this.floatPoint = null
      }
      $this.positions = []
      $this.destroy()
      $this.floatPoint = null
      $this.arrowEntity = null
      $this.clearPoint()
      $this.label.style.display = 'none'
      return
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    this.handler.setInputAction(function (evt) {
      //单机开始绘制
      var cartesian
      cartesian = $this.getCatesian3FromPX(evt.position, $this.viewer)
      if (!cartesian) return

      if ($this.positions.length == 0) {
        $this.floatPoint = $this.createPoint(cartesian)
      }
      if ($this.positions.length > 3) {
        // //结束绘制
        var point = $this.createPoint(cartesian)
        point.wz = $this.positions.length
        $this.pointArr.push(point)
        for (var i = 0; i < $this.pointArr.length; i++) {
          $this.pointArr[i].show = false
        }
        // if ($this.floatPoint) {
        //   //移除动态点
        //   $this.floatPoint.show = false
        //   $this.viewer.entities.remove($this.floatPoint)
        //   $this.floatPoint = null
        // }
        // $this.handler.destroy()
        // return
      } else {
        $this.positions.push(cartesian)
        var point = $this.createPoint(cartesian)
        if ($this.positions.length > 2) {
          point.wz = $this.positions.length - 1 //点对应的在positions中的位置  屏蔽mouseMove里往postions添加时 未创建点
        } else {
          point.wz = $this.positions.length //点对应的在positions中的位置
        }
        $this.pointArr.push(point)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    this.handler.setInputAction(function (evt) {
      $this.label.style.display = 'block'
      $this.label.style.left = evt.endPosition.x + 10 + 'px'
      $this.label.style.top = evt.endPosition.y + 15 + 'px'
      //移动时绘制面

      // var ray = viewer.camera.getPickRay(evt.endPosition);
      // if (!ray) return;
      // var cartesian = viewer.scene.globe.pick(ray, $this.viewer.scene);
      var cartesian
      cartesian = $this.getCatesian3FromPX(evt.endPosition, $this.viewer)
      if (!cartesian) {
        $this.label.innerHTML = '超出地球范围'
        return
      } else {
        $this.label.innerHTML = '左键添加点，右键结束'
        if ($this.positions.length < 2) return
        $this.floatPoint.position.setValue(cartesian)
        if ($this.positions.length >= 2) {
          if (!Cesium.defined($this.arrowEntity)) {
            $this.positions.push(cartesian)
            $this.arrowEntity = $this.showArrowOnMap1($this.positions)
            $this.arrowEntity.objId = $this.objId
          } else {
            $this.positions.pop()
            $this.positions.push(cartesian)
          }
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  }

  showArrowOnMap1(positions) {
    var $this = this
    var update = function () {
      //计算面
      if (positions.length < 3) {
        return null
      }
      var lnglatArr = []
      for (var i = 0; i < positions.length; i++) {
        var lnglat = $this.cartesianToLatlng(positions[i])
        lnglatArr.push(lnglat)
      }
      var res = xp.algorithm.doubleArrow(lnglatArr)
      var returnData = []
      var index = JSON.stringify(res.polygonalPoint).indexOf('null')
      if (index == -1) returnData = res.polygonalPoint
      return new Cesium.PolygonHierarchy(returnData)
    }
    return this.viewer.entities.add({
      polygon: new Cesium.PolygonGraphics({
        hierarchy: new Cesium.CallbackProperty(update, false),
        show: true,
        fill: true,
        material: $this.fillMaterial
      })
    })
  }

  // 曲线
  freeLine(plottingIndex) {
    // this.handler.destroy()
    this.destroy()
    var $this = this
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    var line = undefined //全局线对象
    var linearr = [] //线的坐标存储
    let arr = []
    //鼠标点击事件监听
    this.handler.setInputAction(event => {
      var cartesian = $this.getCatesian3FromPX(event.position)
      if (Cesium.defined(cartesian)) {
        let radiansPos = Cesium.Cartographic.fromCartesian(cartesian)
        let lon = Cesium.Math.toDegrees(radiansPos.longitude)
        let lat = Cesium.Math.toDegrees(radiansPos.latitude)

        //添加一个线对象
        if (!line) {
          linearr.push(cartesian)
          arr.push({
            lon,
            lat
          })
          line = viewer.entities.add({
            polyline: {
              positions: new Cesium.CallbackProperty(function () {
                return linearr
              }, false),

              width: 3,
              material: Cesium.Color.RED,
              clampToGround: true
            }
          })
        }
      }
      //获取世界坐标点
      // var pick = viewer.camera.getPickRay(event.position)
      // var cartesian = viewer.scene.globe.pick(pick, viewer.scene)
      // // 转为坐标
      // let clickPosition = viewer.scene.camera.pickEllipsoid(event.position)

      // //如果世界坐标点存在
      // if (clickPosition) {
      //   let radiansPos = Cesium.Cartographic.fromCartesian(clickPosition)
      //   let lon = Cesium.Math.toDegrees(radiansPos.longitude)
      //   let lat = Cesium.Math.toDegrees(radiansPos.latitude)

      //   //添加一个线对象
      //   if (!line) {
      //     linearr.push(cartesian)
      //     arr.push({
      //       lon,
      //       lat
      //     })
      //     line = viewer.entities.add({
      //       polyline: {
      //         positions: new Cesium.CallbackProperty(function () {
      //           return linearr
      //         }, false),

      //         width: 3,
      //         material: Cesium.Color.RED,
      //         clampToGround: true
      //       }
      //     })
      //   }
      // }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    //鼠标移动事件监听
    this.handler.setInputAction(event => {
      $this.label.style.display = 'block'
      $this.label.style.left = event.endPosition.x + 10 + 'px'
      $this.label.style.top = event.endPosition.y + 15 + 'px'
      var cartesian = $this.getCatesian3FromPX(event.endPosition)

      if (Cesium.defined(cartesian)) {
        $this.label.innerHTML = '右键结束'
        if (line) {
          //考虑在鼠标移动的一瞬间,linearr应该增加一个坐标点,当再次移动时,该坐标点应该更换
          linearr[linearr.length] = cartesian
        }
      } else {
        $this.label.innerHTML = '超出地球范围'
      }
      var pick = viewer.camera.getPickRay(event.endPosition)
      var cartesian = viewer.scene.globe.pick(pick, viewer.scene)

      if (cartesian) {
        $this.label.innerHTML = '右键结束'
        if (line) {
          //考虑在鼠标移动的一瞬间,linearr应该增加一个坐标点,当再次移动时,该坐标点应该更换
          linearr[linearr.length] = cartesian
        }
      } else {
        $this.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    // 左键双击或右键单击时停止绘制
    this.handler.setInputAction(function () {
      $this.label.style.display = 'none'
      // 停止监听 关闭事件句柄
      // $this.handler.destroy()
      $this.destroy()
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    this.handler.setInputAction(function (click) {
      // $this.handler.destroy()
      $this.destroy()
      $this.label.style.display = 'none'
      let point_arr = [] //坐标数组
      linearr.forEach(val => {
        let polyObj = {}
        let cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(val)

        polyObj.lon = Cesium.Math.toDegrees(cartographic.longitude)
        polyObj.lat = Cesium.Math.toDegrees(cartographic.latitude)
        polyObj.height = Cesium.Math.toDegrees(cartographic.height)
        // point_arr.push([polyObj.lon, polyObj.lat])
        point_arr.push(polyObj)
        plottingIndex.value = null
      })
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  clearAll() {
    // this.handler.destroy()
    this.destroy()
    this.viewer.entities.removeAll()
  }

  // 旗标
  curveFlags(type, plottingIndex) {

    //加载
    var $this = this
    function addloadCurveFlags(data, type) {
      console.log(data);
      let componentspolygon = []
      let componentspolyline = []
      if (data.length < 2) return
      // 取第一个
      let startPoint = data[0]
      // 取最后一个
      let endPoint = data[data.length - 1]
      if (type == 0) {
        // 上曲线起始点
        let point1 = startPoint
        // 上曲线第一控制点
        let point2 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], (endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
        // 上曲线第二个点
        let point3 = [(startPoint[0] + endPoint[0]) / 2, startPoint[1]]
        // 上曲线第二控制点
        let point4 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], -(endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
        // 上曲线结束点
        let point5 = [endPoint[0], startPoint[1]]
        // 下曲线结束点
        let point6 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
        // 下曲线第二控制点
        let point7 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 3) / 8 + startPoint[1]]
        // 下曲线第二个点
        let point8 = [(startPoint[0] + endPoint[0]) / 2, (startPoint[1] + endPoint[1]) / 2]
        // 下曲线第一控制点
        let point9 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 5) / 8 + startPoint[1]]
        // 下曲线起始点
        let point10 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
        // 旗杆底部点
        let point11 = [startPoint[0], endPoint[1]]
        // 计算上曲线
        let curve1 = getBezierPoints([point1, point2, point3, point4, point5])
        // 计算下曲线
        let curve2 = getBezierPoints([point6, point7, point8, point9, point10])
        // 合并
        componentspolygon = curve1.concat(curve2)

        componentspolyline = curve1.concat(curve2)
        componentspolyline.push(LatlngTocartesian(point1))
        componentspolyline.push(LatlngTocartesian(point11))
      } else if (type == 1) {
        console.log(data);
        var point1 = [endPoint[0], startPoint[1]]
        var point2 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
        var point3 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
        var point4 = [startPoint[0], endPoint[1]]

        componentspolygon = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, point3]))
        componentspolyline = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, point3, startPoint, point4]))
      } else {
        var point1 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
        var point2 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
        var point3 = [startPoint[0], endPoint[1]]
        componentspolygon = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2]))
        componentspolyline = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, startPoint, point3]))
      }
      var shape = $this.viewer.entities.add({
        Type: 'DrawCurveFlag',
        Position: data,
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(componentspolygon),
          material: Cesium.Color.RED,
          clampToGround: true
        },
        polyline: {
          //使用cesium的peoperty
          positions: componentspolyline,
          show: true,
          material: Cesium.Color.YELLOW,
          width: 5,
          clampToGround: true
        }
      })
      $this.entitiesCurveFlag.push(shape)
      return shape
    }
    function scalarArrayEquals(array1, array2) {
      return array1.length == array2.length && array1.every(function (v, i) { return v === array2[i] });
    }
    //创建曲线旗标
    function createCurveFlag(type, plottingIndex) {

      var polygon = $this.viewer.entities.add({
        polygon: {
          hierarchy: new Cesium.CallbackProperty(function () {
            if ($this.positions.length < 2) return
            let lonlat = []
            let components = []
            let length = $this.positions.length

            for (let i = 0; i < length; i++) {
              lonlat.push($this.cartesianToLatlng($this.positions[i]))
            }
            // 取第一个
            let startPoint = lonlat[0]
            // 取最后一个
            let endPoint = lonlat[lonlat.length - 1]

            if (type == 0) {
              // 上曲线起始点
              let point1 = startPoint
              // 上曲线第一控制点
              let point2 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], (endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
              // 上曲线第二个点
              let point3 = [(startPoint[0] + endPoint[0]) / 2, startPoint[1]]
              // 上曲线第二控制点
              let point4 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], -(endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
              // 上曲线结束点
              let point5 = [endPoint[0], startPoint[1]]
              // 下曲线结束点
              let point6 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              // 下曲线第二控制点
              let point7 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 3) / 8 + startPoint[1]]
              // 下曲线第二个点
              let point8 = [(startPoint[0] + endPoint[0]) / 2, (startPoint[1] + endPoint[1]) / 2]
              // 下曲线第一控制点
              let point9 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 5) / 8 + startPoint[1]]
              // 下曲线起始点
              let point10 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              // 旗杆底部点
              let point11 = [startPoint[0], endPoint[1]]
              // 计算上曲线
              let curve1 = getBezierPoints([point1, point2, point3, point4, point5])
              // 计算下曲线
              let curve2 = getBezierPoints([point6, point7, point8, point9, point10])
              // 合并
              components = curve1.concat(curve2)
            } else if (type == 1) {

              console.log(lonlat);
              if (scalarArrayEquals(lonlat[0], lonlat[1])) return
              var point1 = [endPoint[0], startPoint[1]]
              var point2 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point3 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point4 = [startPoint[0], endPoint[1]]
              components = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, point3]))
            } else {
              if (scalarArrayEquals(lonlat[0], lonlat[1])) return
              var point1 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point2 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point3 = [startPoint[0], endPoint[1]]
              components = [startPoint, point1, point2]

              components = Cesium.Cartesian3.fromDegreesArray([].concat.apply([], components))
            }
            return new Cesium.PolygonHierarchy(components)
          }, false),

          material: Cesium.Color.RED,
          clampToGround: true
        },
        polyline: {
          //使用cesium的peoperty
          positions: new Cesium.CallbackProperty(function () {
            if ($this.positions.length < 2) return
            let lonlat = []
            let components = []
            let length = $this.positions.length
            for (let i = 0; i < length; i++) {
              lonlat.push(cartesianToLatlng($this.positions[i]))
            }
            // 取第一个
            let startPoint = lonlat[0]
            // 取最后一个
            let endPoint = lonlat[lonlat.length - 1]
            if (type == 0) {
              // 上曲线起始点
              let point1 = startPoint
              // 上曲线第一控制点
              let point2 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], (endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
              // 上曲线第二个点
              let point3 = [(startPoint[0] + endPoint[0]) / 2, startPoint[1]]
              // 上曲线第二控制点
              let point4 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], -(endPoint[1] - startPoint[1]) / 8 + startPoint[1]]
              // 上曲线结束点
              let point5 = [endPoint[0], startPoint[1]]
              // 下曲线结束点
              let point6 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              // 下曲线第二控制点
              let point7 = [((endPoint[0] - startPoint[0]) * 3) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 3) / 8 + startPoint[1]]
              // 下曲线第二个点
              let point8 = [(startPoint[0] + endPoint[0]) / 2, (startPoint[1] + endPoint[1]) / 2]
              // 下曲线第一控制点
              let point9 = [(endPoint[0] - startPoint[0]) / 4 + startPoint[0], ((endPoint[1] - startPoint[1]) * 5) / 8 + startPoint[1]]
              // 下曲线起始点
              let point10 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              // 旗杆底部点
              let point11 = [startPoint[0], endPoint[1]]
              // 计算上曲线
              let curve1 = getBezierPoints([point1, point2, point3, point4, point5])
              // 计算下曲线
              let curve2 = getBezierPoints([point6, point7, point8, point9, point10])
              // 合并
              components = curve1.concat(curve2)
              components.push(LatlngTocartesian(point1))
              components.push(LatlngTocartesian(point11))
              return components
            } else if (type == 1) {
              var point1 = [endPoint[0], startPoint[1]]
              var point2 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point3 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point4 = [startPoint[0], endPoint[1]]
              return Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, point3, startPoint, point4]))
            } else {
              var point1 = [endPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point2 = [startPoint[0], (startPoint[1] + endPoint[1]) / 2]
              var point3 = [startPoint[0], endPoint[1]]

              return Cesium.Cartesian3.fromDegreesArray([].concat.apply([], [startPoint, point1, point2, startPoint, point3]))
            }
          }, false),
          show: true,
          material: Cesium.Color.YELLOW,
          width: 5,
          clampToGround: true
        }
      })
      $this.entitiesCurveFlag.push(polygon)
      return polygon
    }
    function createPoint(cartesian) {
      var point = $this.viewer.entities.add({
        position: cartesian,
        point: {
          pixelSize: 10,
          color: Cesium.Color.YELLOW
        }
      })
      $this.entitiesPoint.push(point)
      return point
    }
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.handler.setInputAction(function (evt) {
      //单机开始绘制
      //屏幕坐标转地形上坐标
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (Cesium.defined(cartesian)) {
        if ($this.positions.length == 0) {
          $this.positions.push(cartesian.clone())
          $this.identificationPoint = createPoint(cartesian)
          createPoint(cartesian) // 绘制点
          $this.positions.push(cartesian)
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (evt) {
      $this.label.style.display = 'block'
      $this.label.style.left = evt.endPosition.x + 10 + 'px'
      $this.label.style.top = evt.endPosition.y + 15 + 'px'
      //移动时绘制线
      if ($this.positions.length < 2) return
      var cartesian = $this.getCatesian3FromPX(evt.endPosition)
      if (Cesium.defined(cartesian)) {
        $this.label.innerHTML = '左键添加点，右键结束'
        if (!Cesium.defined($this.CurveFlag)) {
          $this.CurveFlag = createCurveFlag(type)
        } else {
          $this.positions.pop()
          $this.positions.push(cartesian)
        }
        $this.identificationPoint.position.setValue(cartesian)
      } else {
        $this.label.innerHTML = '超出地球范围'
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(function (evt) {
      if (!$this.CurveFlag) return
      var cartesian = $this.getCatesian3FromPX(evt.position)
      $this.positions.pop()
      $this.positions.push(cartesian)
      createPoint(cartesian) // 绘制点
      $this.CurveFlagData = $this.positions.concat()
      $this.viewer.entities.remove($this.CurveFlag) //移除
      $this.CurveFlag = null
      $this.positions = []
      $this.identificationPoint.position.setValue(cartesian)
      var lnglatArr = []
      for (var i = 0; i < $this.CurveFlagData.length; i++) {
        var lnglat = cartesianToLatlng($this.CurveFlagData[i])
        lnglatArr.push(lnglat)
      }
      $this.CurveFlagData = lnglatArr
      var CurveFlag = addloadCurveFlags([$this.CurveFlagData[0], $this.CurveFlagData[$this.CurveFlagData.length - 1]], type) //加载
      $this.entitiesCurveFlag.push(CurveFlag)
      $this.CurveFlagLast = CurveFlag
      clearPoint()
      $this.destroy()
      plottingIndex.value = null
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

    function cartesianToLatlng(cartesian) {
      var latlng = $this.viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
      var lat = Cesium.Math.toDegrees(latlng.latitude)
      var lng = Cesium.Math.toDegrees(latlng.longitude)
      return [lng, lat]
    }

    function LatlngTocartesian(latlng) {
      let cartesian3 = Cesium.Cartesian3.fromDegrees(latlng[0], latlng[1])
      return cartesian3
    }

    function clearPoint() {
      for (var i = 0; i < $this.entitiesPoint.length; i++) {
        $this.viewer.entities.remove($this.entitiesPoint[i])
      }
      $this.entitiesPoint = [] //脏数据
    }

    // 贝塞尔曲线
    function getBezierPoints(points) {
      let $this = this
      if (points.length <= 2) {
        return points
      } else {
        let bezierPoints = []
        let n = points.length - 1
        for (let t = 0; t <= 1; t += 0.01) {
          let [x, y] = [0, 0]
          for (let index = 0; index <= n; index++) {
            let factor = getBinomialFactor(n, index)
            let a = Math.pow(t, index)
            let b = Math.pow(1 - t, n - index)
            x += factor * a * b * points[index][0]
            y += factor * a * b * points[index][1]
          }
          bezierPoints.push(LatlngTocartesian([x, y]))
        }
        bezierPoints.push(LatlngTocartesian(points[n]))
        return bezierPoints
      }
    }

    /**
     * 获取二项分布
     * @param n
     * @param index
     * @returns {number}
     */
    function getBinomialFactor(n, index) {
      return getFactorial(n) / (getFactorial(index) * getFactorial(n - index))
    }

    /**
     * 获取阶乘数据
     * @param n
     * @returns {number}
     */
    function getFactorial(n) {
      let result = 1
      switch (n) {
        case n <= 1:
          result = 1
          break
        case n === 2:
          result = 2
          break
        case n === 3:
          result = 6
          break
        case n === 24:
          result = 24
          break
        case n === 5:
          result = 120
          break
        default:
          for (let i = 1; i <= n; i++) {
            result *= i
          }
          break
      }
      return result
    }
  }

  // 剖面分析
  ProfileAnalysis(measureIndex, echartsRef, pmShow) {
    var heightList = []
    var $this = this
    // this.handler.destroy()
    this.destroy()
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)

    var $this = this
    var poly = null
    var distance = 0
    this.handler.setInputAction((click) => {
      // const ray = this.viewer.camera.getPickRay(click.position);
      // const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
      var cartesian = $this.getCatesian3FromPX(click.position)

      if (Cesium.defined(cartesian)) {

        const length = this.positions.length
        if (this.positions.length == 0) {
          this.positions.push(cartesian.clone())
        }
        poly = new PolyLinePrimitive($this.positions)
        this.positions.push(cartesian)
        distance = getSpaceDistance($this.positions)
        var textDisance
        textDisance = distance + 'm'
        $this.viewer.entities.add({
          name: '空间直线距离',
          position: $this.positions[$this.positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.DEEPSKYBLUE,
            outlineWidth: 3,
            // clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
          label: {
            text: textDisance,
            font: '18px sans-serif',
            fillColor: Cesium.Color.DARKORANGE,
            fillColor: Cesium.Color.RED,
            pixelOffset: new Cesium.Cartesian2(20, -20),
            clampToGround: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,
          }
        })
        if (length >= 2) {
          console.log(222);
          // 插值运算
          this.interPoints(this.positions, 10, echartsRef, distance)
        }
      }



    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (movement) {
      // $this.handler.destroy() // 关闭事件句柄
      $this.destroy()
      measureIndex.value = null
      pmShow.value = true
      $this.positions = []

      $this.interData = []
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

  }



  /**
   * @name: interPoints
   * @Date: 2022-09-27 17:24:02
   * @description: 坐标点插值positionsDegrees
   * @param {any} positions 坐标点数组
   * @param {number} interNumber 取样点个数
   */
  interPoints(positions, interNumber, echartsRef, distance) {

    const posDegrees = [];
    for (let index = 0; index < positions.length; index++) {
      const element = positions[index];
      const ellipsoid = this.viewer.scene.globe.ellipsoid;
      const cartographic = ellipsoid.cartesianToCartographic(element);
      let x = Cesium.Math.toDegrees(cartographic.longitude)
      let y = Cesium.Math.toDegrees(cartographic.latitude)
      let z = cartographic.height
      let data = { longitude: x, latitude: y, height: z }
      posDegrees.push(data);
    }
    let offset, x, y, z;
    for (let i = 0; i < interNumber; ++i) {
      offset = i / (interNumber - 1);
      // 做插值
      x = Cesium.Math.lerp(posDegrees[posDegrees.length - 2].longitude, posDegrees[posDegrees.length - 1].longitude, offset);
      y = Cesium.Math.lerp(posDegrees[posDegrees.length - 2].latitude, posDegrees[posDegrees.length - 1].latitude, offset);
      z = Cesium.Math.lerp(posDegrees[posDegrees.length - 2].height, posDegrees[posDegrees.length - 1].height, offset);

      this.interData.push([x, y, z]);
    }
    //查询地图的地形高度
    const terrainProvider = new Cesium.CesiumTerrainProvider({
      url: 'http://localhost:666/map/dixing'
    })
    let interDataMap = this.interData.map((d) => Cesium.Cartographic.fromDegrees(...d))


    Cesium.sampleTerrainMostDetailed(terrainProvider, interDataMap)
      .then(positions => {
        // console.log(positions);
        const heightList = positions.map(d => {
          // console.log(d);
          return {
            height: d.height,
            longitude: Cesium.Math.toDegrees(d.longitude),
            latitude: Cesium.Math.toDegrees(d.latitude)
          }
        })
        this.initChart(heightList, echartsRef, distance)
      })
  }

  /**
   * @name: initChart
   * @Date: 2022-09-28 09:12:39
   * @description: 生成剖面图
   * @param {any} data 高程数组
   */
  initChart(data, echartsRef, distance) {
    console.log(data);
    console.log(echartsRef);
    console.log(distance);
    var $this = this
    // console.log('生成剖面图');
    this.disposeChart(echartsRef);
    let myChart = echarts.init(echartsRef,);

    var jls = []
    let jl
    for (let i = 0; i <= data.length - 1; i++) {
      if (i == 0) {
        jl = 0
        jls.push(jl)
      } else {
        // jl = ((this.distance / (data.length + 1)) * (i + 2)).toFixed(2)
        jl = (distance / (data.length + 1) * (i + 2)).toFixed(2)
        jls.push(jl)
      }
    }
    // console.log(jls);
    let heights = []
    data.forEach(e => {
      heights.push(e.height)
    })
    // console.log(heights);
    myChart.setOption({

      dataZoom: [
        {
          type: 'inside',
          throttle: 500
        }
      ],
      xAxis: [
        {
          name: '行程(米)',
          nameTextStyle: {
            color: 'rgba(168, 230, 243, 1)',
            fontSize: 14,
            padding: [0, 0, 0, -10]
          },
          type: 'category',
          // boundaryGap: !1,
          axisLine: {
            show: true
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#fff',
            }
          },
          data: jls,
        }
      ],
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          console.log(params);
          console.log(data);
          let lon = data[params[0].dataIndex].longitude
          let lat = data[params[0].dataIndex].latitude
          let alt = data[params[0].dataIndex].height

          let cartesian = Cesium.Cartesian3.fromDegrees(lon, lat, alt)

          $this.clearBillboard()
          $this.createBillboard(cartesian)
          let str = `当前位置<br>距起点${jls[params[0].dataIndex]}米<br>海拔：${data[params[0].dataIndex].height.toFixed(0)}米<br>经度：${data[params[0].dataIndex].longitude.toFixed(6)}<br>纬度：${data[params[0].dataIndex].latitude.toFixed(6)}`
          return str
        }
      },

      yAxis: [
        {

          splitNumber: 10,

          // z: 3,
          // max: Math.ceil(heights[heights.length - 1]) + 200,
          // min: Math.floor(heights[0]) - 200,
          // interval: Math.ceil(Math.max.apply(null, data) / 5),
          // max: Math.ceil(Math.max.apply(null, data) / 5) * 5,
          scale: true,
          type: 'value',
          name: '高程(米)',
          nameTextStyle: {
            color: 'rgba(168, 230, 243, 1)',
            fontSize: 14,
            padding: [0, 0, 10, -40]
          },
          axisLabel: {
            // rotate: 60,
            // formatter: '{value} 米'
            textStyle: {
              color: '#fff',
            }
          }
        }
      ],
      series: [
        {
          name: '高程值',
          type: 'line',
          smooth: true,
          // symbol: 'none',
          sampling: 'average',
          symbol: 'circle', //将小圆点改成实心 不写symbol默认空心
          symbolSize: 6, //小圆点的大小
          lineStyle: {
            width: 2,
            color: '#6AF0FF', //线条颜色
            // type: "dotted", //'dotted'虚线 'solid'实线
            shadowColor: '#6AF0FF', //阴影颜色
            shadowBlur: 5, //阴影的模糊大小。
            shadowOffsetX: 5, // 阴影水平方向上的偏移距离
            shadowOffsetY: 5 // 阴影垂直方向上的偏移距离
          },

          itemStyle: {
            normal: {
              color: 'rgb(255, 70, 131)'
            }
          },
          areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(255, 158, 68)'
                },
                {
                  offset: 1,
                  color: 'rgb(255, 70, 131)'
                }
              ])
            }
          },
          data: data.map(e => {
            return e.height
          }),
        },

      ]
    })
    window.onresize = () => {
      myChart.resize();
    };
  }

  disposeChart(echartsRef) {
    echarts.dispose(echartsRef);
  }
}
